package cn.wyu.web;

import cn.wyu.pojo.User;
import cn.wyu.service.UserService;
import cn.wyu.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login.do")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //处理中文乱码问题
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.接收用户名和密码
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        System.out.println("用户名："+loginName+","+"密码："+password);

        //2.将数据提交给业务层
        UserService us = new UserServiceImpl();
        User user = us.findByLoginName(loginName,password);
        if(user != null)
        {
            //登录成功,跳到首页
            //将用户信息保存到session供其他页面访问
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            System.out.println("登录成功"+user);

            //重定向到首页
            response.sendRedirect("index.do");

        }
        else
        {
            //登录失败，给提示
            //转发到登录页面
            request.setAttribute("loginmsg","密码或用户名错误");
            System.out.println("登录失败");
            request.getRequestDispatcher("login.jsp").forward(request,response);

        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }
}
